const { static } = require("express");

module.exports = class Banner extends require("./model") {
    /**
       * 获取轮播图
       * @param {integer} num 条目数
       */
    static getBanner(id) {
        return new Promise((resolve, reject) => {
            let sql = "SELECT * FROM banner WHERE 1=1 ";
            sql += id !== undefined ? `AND id = ${id} ` : '';
            this.query(sql)
                .then((res) => {
                    resolve(res);
                })
                .catch((err) => {
                    console.log(`获取轮播图失败失败：${err.message}`);
                    reject(err);
                });
        });
    }
    /**
   *  上传轮播图
   * @param {Object} banner 轮播图对象
   */
    static updateBanner(banner) {
        return new Promise((resolve, reject) => {
            banner.forEach(item => {
                this.getBanner(item.id).then(res => {
                    if (res.length > 0 && item.id !== undefined) {
                        // 编辑
                        let sql = `UPDATE banner SET bannerLink = ?,bannerImg = ?, WHERE id = ?`
                        const { bannerLink, bannerImg, id } = item
                        this.query(sql, [bannerLink, bannerImg, id]).then(data => {
                            resolve({
                                affectedRows: data.affectedRows,
                                msg: '编辑'
                            });
                        })
                    } else {
                        // 新增
                        let sql = "INSERT INTO banner SET ?";
                        this.query(sql, item).then(data => {
                            resolve({
                                affectedRows: data.affectedRows,
                                msg: '添加'
                            });
                        })
                    }
                })
            })
        });
    }
}